/*
 * designassignment2.c
 *
 * Created: 3/2/2014 5:30:15 AM
 *  Author: Yosemit Xolalpa Rosales
 */
 #include <avr/io.h>
 #include <avr/interrupt.h>
 #define F_CPU 1000000UL	//1MHz clock frequency
 #include <util/delay.h>

 int volatile ctrInt = 0;	//initialize global variable (counter interrupts)

 void delay_waveform();
 int main(void)
 {
	 int bCounter = 0;		//initialize counter
	 DDRD = 0b1011;			//set DDRD.3(Interrupt Flag), DDRD.0(DelayWaveform) and DDRD.1(Status) as output
	 DDRB = 0xFF;			//DDRB as output
	 EICRA = (1<<ISC01);	//enable external interrupt ISC01 on the falling edge
	 EIMSK = (1<<INT0);     //enable external Mask INT0
	 sei ();				//enable interrupts

	 
	 while(1)
	 {
		 delay_waveform();
		 if(PORTD & (1<<PD0))		//if PD0 is set
		 {
			 delay_waveform();		//call to the delay subroutine
			 PORTB = ++bCounter;	//this 8bit counter will toggle for PD0 falling edge
			 if(bCounter>255)		//counter will reset once it reaches 255 (1111 1111 in binary)
			 {  
				bCounter = 0;
			 }
			 if((bCounter%20)==0)	//toggle PD1 for every 10 falling edge
			 {           
				PORTD ^= 1<<PD1;
			 }
		 }
	 }
 }


 ISR (INT0_vect) //ISR for external interrupt 0
 {
	 ++ctrInt;
	 if (ctrInt == 2)
	 {
		 PORTD = (1<<PD3);			// output PORTD.3
		 ctrInt = 0;				// reset global variable
	 }
 }
 
 void delay_waveform()
 {
	_delay_ms(250.0);				// 50% Duty cycle
	PORTD ^= 1<<PD0;				// output on PORTD.0
 }
 